package service;
import java.io.File;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.CellType;

import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import common.kit.AppMsgKit;
import common.kit.ExcelKit;
import common.kit.PageSql;
import enums.ServicerStatus;
import enums.WxuserRole;
import model.Servicer;
import model.Staff;
import model.Wxuser;

public class ServicerService extends BaseService {

	public Page<Record> getPage(Kv kv , Integer pageNumber , Integer pageSize) {
		kv.set("ts.isDelete", 0);
		String select = " ts.address,ts.refuseReason,ts.id,ts.createTime,ts.name,ts.license,ts.licensePic,ts.authPic,ts.contacts,ts.mobile,ts.status,ts.remark " ;
	    PageSql pageSql = PageSql.bySelect( kv , select ) ;
	    pageSql.from(" t_servicer ts ") ;
		pageSql.setLikeCondition("ts.name") ; //公司名称	 
		pageSql.setLikeCondition("ts.mobile") ; //手机号码	 
		pageSql.setEqualCondition("ts.status") ; //状态	 
		pageSql.setEqualCondition("ts.isDelete") ; //状态	 
	    pageSql.orderBy(" ts.createTime DESC ");
		Page<Record> page = pageSql.paginate( pageNumber , pageSize) ;
		for (Record record : page.getList()) {
			record.set("statusStr", ServicerStatus.getTitleByValue(record , "status"));
		}
	    return page ;
	}

	public Ret delete(Long id) {
        Servicer servicer = Servicer.dao.findById(id);
        if(null == servicer){
            return fail();
        }
        servicer.setIsDelete(true);
        servicer.update();
        Wxuser.dao.deleteServicer(servicer);
        Staff.dao.deleteByServicerId(servicer.getId());
        return ok() ;
    }

	public Ret save(Servicer servicer) {
		if (servicer.isRepeatName()) {
			return fail("公司名称已存在");
		}
	    Long id = servicer.getId();
	    if(null == id){
	        servicer.save();
	    }else{
	        servicer.update() ;
	    }
	    Wxuser.dao.saveForCompany(servicer.getMobile(), WxuserRole.getSeviser() , servicer.getId() );
	    return ok() ;
	}
	
	public Ret audit(boolean isPass , Long id , String reason) {
		Servicer servicer = Servicer.dao.findById(id);
		if (null == id ) {
			return fail();
		}
		if (!servicer.isAuditingStatus()) {
			return fail("状态已变更");
		}
		if (isPass) {
			servicer.setNormalStatus();
			servicer.setRefuseReason(null);
			//创建账号
			Wxuser.dao.saveForCompany(servicer.getMobile(), WxuserRole.getSeviser(), servicer.getId());
			//下发审核结果通知
			AppMsgKit.sendAuditResultMsg();
		}else {
			servicer.setRefusedStatus();
			servicer.setRefuseReason(reason);
			//下发审核结果通知
			AppMsgKit.sendAuditResultMsg();
		}
		servicer.update();
		return ok() ;
	}
	
	public int saveByName(Servicer servicer) {
		if (StrKit.isBlank(servicer.getName())) {
			return -1 ;
		}
		servicer.setNormalStatus();
		Servicer ex = Servicer.dao.findFirstByName(servicer.getName());
	    if(null == ex){
	    	servicer.save();
	    	Wxuser.dao.saveForCompany(servicer.getMobile(), WxuserRole.getSeviser(), servicer.getId() );
	        return 1 ;
	    }
	    servicer.setId(ex.getId());
	    servicer.update() ;
	    Wxuser.dao.saveForCompany(servicer.getMobile(), WxuserRole.getSeviser(), servicer.getId() );
        return 0 ;
	}
	
	public Ret importExcel(File file){
		ExcelKit excelKit = new ExcelKit(file);
		HSSFSheet hs = excelKit.getHSSheet() ;
	    int first = 1 ;
	    int skipCount = 0  , saveCount = 0 , updateCount = 0 ;
	    for (int i = first; i <= hs.getLastRowNum() ; i++) {
		    HSSFRow row = hs.getRow(i);
		    int firstCellNum = row.getFirstCellNum();//获取所在行的第一个行号
		    int lastCellNum = row.getLastCellNum();//获取所在行的最后一个行号
		    String[] keys = {"name","address","license","contacts","mobile"};
		    Servicer servicer = new Servicer();
			for (int j = firstCellNum; j <lastCellNum; j++) {
				HSSFCell cell = row.getCell(j);
				cell.setCellType(CellType.STRING);
				String value = cell.getStringCellValue() ;
				servicer.set(keys[j], value);
			}
			int count = this.saveByName(servicer);
			if (count == -1) {
				skipCount ++ ;
			}
			if (count == 0) {
				updateCount ++ ;
			}
			if (count == 1) {
				saveCount ++ ;
			}
	    }
	    file.delete();
	    excelKit.close();
	    return Ret.create("saveCount",saveCount).set("updateCount" , updateCount).set("skipCount" , skipCount);
	}
	
	public File exportExcel(Kv kv) {
		ExcelKit excelKit = new ExcelKit();
		HSSFSheet sheet = excelKit.getHSSheet() ;
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = null ;
		String titleString = "公司名称,公司地址,营业执照号,联系人,联系电话";
		String[] titles = titleString.split(",");
		for (int i = 0; i < titles.length; i++) {
			cell = row.createCell(i);
			cell.setCellValue(titles[i]);
		}
		int rowNum = 1 ;
		int pageNumber = 0 ;
		boolean lastPage = false ;
		do {
			pageNumber ++ ;
			Page<Record> page = this.getPage(kv, pageNumber, 200);
			lastPage = page.isLastPage();
			List<Record> list = page.getList() ;
			for (Record record : list) {
				row = sheet.createRow(rowNum);
				String[] arr = { record.getStr("name") , record.getStr("address") , record.getStr("license") , 
						record.getStr("contacts") , record.getStr("mobile") };
				for (int i = 0; i < titles.length; i++) {
					cell = row.createCell(i);
					cell.setCellValue(arr[i]);
				}
				rowNum ++ ;
			}
		} while (!lastPage);
		return excelKit.writeExcel();
	}

	public Ret apply(Servicer servicer) {
		if (servicer.isRepeatName() && servicer.isNormalStatus() ) {
			return fail( "已入驻" );
		}
		Servicer ex = Servicer.dao.findFirstByName(servicer.getName());
		if (null != ex) {
			servicer.setId(ex.getId());
			servicer.setAuditingStatus();
			servicer.update();
			return ok() ;
		}
		servicer.setAuditingStatus();
		servicer.save();
		return ok();
    }
}
